<!-- 审计日志 -->
<template>
  <div class="dashboard-editor-container">
    <div class="xxx" style="margin-top: 10px;">
      <div style="display:flex;justify-content:space-between;">
        <partitionTree :nodeData="nodeData" :DepartmentList="DepartmentList" :addTemplate="true"
          :defaultProps="{ children: 'Children', label: 'Name' }" :expandArray="expandArray" :defaultExpandAll="true"
          @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility"
          @addDepartment="getData">
        </partitionTree>
        <div :style="{ width: containerWidth }" class="box"
          style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <el-row style="background: #fff; padding: 16px 16px 0;">
            <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
            <div class="tabclick">
              <div class="tabitem" @click="handleClick()">
                <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
              </div>
            </div>
            <el-row>
              <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
                <el-tab-pane label="按日统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <barchart :chartData="barchartData" @barclick="barclick" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按终端用户统计" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pieData" @pieclick="echartsClick" title="按终端用户统计" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按聊天工具分类统计" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pieData" @pieclick="echartsClick" title="按聊天工具分类统计" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按聊天对象分类统计" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pieData" @pieclick="echartsClick" title="按聊天对象分类统计" />
                  </el-col>
                </el-tab-pane>
              </el-tabs>
            </el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="padding-right: 8px;">
              <!-- <span class="title">事件日志列表</span> -->
              <el-table stripe border :data="tableData" style="width: 100%; margin-top: 32px" height="calc(100vh - 420px)">
                <el-table-column label="序号" width="60" type="index"
                  :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                <el-table-column label="聊天时间" prop="TransTime"  width="180px"></el-table-column>
                <el-table-column label="聊天终端" prop="DeviceName"  width="220px"></el-table-column>
                <el-table-column label="发送账号" prop="Count" ></el-table-column>
                <el-table-column label="聊天方向" prop="Count" ></el-table-column>
                <el-table-column label="接收账号" prop="Count" ></el-table-column>
                <el-table-column label="聊天内容" prop="Count" ></el-table-column>
                <el-table-column label="操作"  width="80px" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="changeMailGlobal(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
                :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { connrequest } from "@/api/firstPage.js"
import { getNowDay, parseTime, toTree } from "@/utils/index.js";
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart2.vue";
import piechart from "./components/piechart.vue";
import partitionTree from "@/components/partitionTree";  
export default {
  components: { connsearch, barchart, piechart, partitionTree },
  data() {
    let that = this
    return {
      total: 0,
      pageNum: 1,
      pageSize: 10,
      containerWidth: 'calc(100% - 275px)',
      tab: false,
      tableData: [],
      nodeData:[],
      DepartmentList:[],
      expandArray:[0, 100],
      pieData: [],
      barchartData: { xAxis: [], series: [] },
      searchform: {},
      searchobj: {},
      tabTitle: '按日统计分析',
      formOptions: [
        {
          col: 10,
          label: "日期",
          prop: "timeRange",
          element: "el-date-picker",
          type: "",
          events: {
            input(val) {
              that.searchform.timeRange = val
            }
          }
        },
        {
          col: 6,
          label: "资产名称",
          prop: "DeviceUUID",
          element: "el-cascader",
          initValue: "",
          placeholder: "请选择资产",
          options: [],
          props: { emitPath: false, checkStrictly: false, lazy: true, lazyLoad: that.lazyLoad },
          events: {
            input(val) {
              that.searchform.DeviceUUID = val
            }
          }
        },
        {
          col: 6,
          label: "聊天内容", // label文字
          prop: "DeviceName", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入聊天内容,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceName = val
            }
          }
        }
      ]
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let xTime = new Date().getTime()
    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime() 
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    // let arr = [ parseTime(startTime), parseTime(xTime)]
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.$set(this.searchform, 'result', 2)
    this.getData()
    this.GetScreenLogSumByDate()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.GetDepartmentDeviceSumTree()
  },
  methods: {
    // 获取子节点的资产
    async lazyLoad(node, resolve) {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
        Filter: {
          DepartmentID: node?.data?.ID
        }
      }
      const res = await connrequest('GetDevice', data)
      let arr = []
      res.Data.map(item => {
        arr.push({ SubClass: item.DeviceName, value: item.DeviceUUID, children: undefined, leaf: true })
      })
      resolve(arr)
    },
    // 获取部门树
    async GetDepartmentDeviceSumTree() {
      const res = await connrequest('GetDepartmentDeviceSumTree')
      res.Data.Name = res.Data.RootName
      this.nodeData = toTree(res.Data.Department, res.Data.RootName)
      this.DepartmentList = res.Data.Department
      res.Data.Department.map(item => {
        item.SubClass = item.Name
        item.value = item.ID
        return item
      })
      this.formOptions.map(item => {
        if (item.label === '资产名称') {
          item.options = res.Data.Department
        }
      })
    },
    handleNodeClick(nodeData){
      this.choseArea = {DepartmentID: nodeData.data.ID}
      this.getData(this.choseArea)
    },
    toggleVisibility(isHidden) { 
      if(isHidden)
        this.containerWidth = '100%';
      else 
        this.containerWidth = 'calc(100% - 275px)';
    },
    async getData(searchobj = {}) {     
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Result: this.searchform.result,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetScreenLogOverview', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime, '{y}-{m}-{d} {h}:{i}:{s}')
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 查看详情
    changeMailGlobal(row) {
      this.$router.push(`/journal/recordingDetails?DeviceUUID=${row.DeviceUUID}&&DepartmentID=${row.DepartmentID || ''}&&StartTime=${this.searchform.timeRange?.[0]}&&EndTime=${this.searchform.timeRange?.[1]}`)
    },
    handleClick() {
      this.tab = !this.tab
    },
    // 获取事件日期统计
    async GetScreenLogSumByDate() {
      let xAxis = []
      let series = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || ''
        }
      }
      const res = await connrequest('GetScreenLogSumByDate', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        xAxis.push(item.TransDate)
        series.push(item.Count)
      })
      this.barchartData = { xAxis, series }
    },
    async GetScreenLogSumByDeviceName() {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || ''
        }
      }
      const res = await connrequest('GetScreenLogSumByDeviceName', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ name: item.DeviceName, value: item.Count })
      })
      this.pieData = arr
    },
    barclick(val) {
      this.pageNum = 1
      this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
      this.getData(this.searchobj)
    },
    tabClick(row) {
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计分析':
          this.GetScreenLogSumByDate()
          break;
        case '按审计类型统计分析':
          this.GetScreenLogSumByDeviceName()
          break;
      }
    },
    echartsClick(val, title) {
      this.pageNum = 1
      if (title === '按日统计分析') {
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.getData(this.searchobj)
      } else if (title === '按审计类型统计分析') {
        this.searchobj = { Operate: val }
        this.getData(this.searchobj)
      }
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = { ...val }
      if (this.searchform.timeRange) {
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
      switch (this.tabTitle) {
        case '按日统计分析':
          this.GetScreenLogSumByDate()
          break;
        case '按审计类型统计分析':
          this.GetScreenLogSumByDeviceName()
          break;
      }
    },
    // 重置
    reset() {
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime() 
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$set(this.searchform, 'result', 2)
      this.$refs.connsearch.addInitValue()
      this.getData()
      switch (this.tabTitle) {
        case '按日统计分析':
          this.GetScreenLogSumByDate()
          break;
        case '按审计类型统计分析':
          this.GetScreenLogSumByDeviceName()
          break;
      }
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      this.getData({ ...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] || '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] || '' })
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.getData({ ...this.searchobj, StartTime: this.searchobj?.StartTime || this.searchform.timeRange?.[0] || '', EndTime: this.searchobj?.EndTime || this.searchform.timeRange?.[1] || '' })
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";
</style>